/*
 * Copyright, Aspect Security, Inc.
 *
 * This file is part of JavaSnoop.
 *
 * JavaSnoop is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * JavaSnoop is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with JavaSnoop.  If not, see <http://www.gnu.org/licenses/>.
 */
package com.aspect.snoop;

import java.io.IOException;

import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.SwingWorker;

import org.apache.log4j.Logger;
import org.jdesktop.application.Action;
import org.jdesktop.application.FrameView;
import org.jdesktop.application.SingleFrameApplication;

import com.aspect.snoop.agent.AgentCommunicationException;
import com.aspect.snoop.agent.AgentJar;
import com.aspect.snoop.agent.AgentJarCreator;
import com.aspect.snoop.ui.JavaSnoopAboutBox;
import com.aspect.snoop.ui.choose.process.ChooseProcessView;
import com.aspect.snoop.ui.choose.process.NewProcessInfoView;
import com.aspect.snoop.util.AttachUtil;
import com.aspect.snoop.util.UIUtil;
import com.sun.tools.attach.AgentInitializationException;
import com.sun.tools.attach.AgentLoadException;
import com.sun.tools.attach.AttachNotSupportedException;

public class StartupView extends FrameView {

    private static final Logger logger = Logger.getLogger(StartupView.class);

    public StartupView(SingleFrameApplication app) {
        super(app);

        initComponents();
    }

    @Action
    public void showAboutBox() {
        if (aboutBox == null) {
            JFrame mainFrame = JavaSnoop.getApplication().getMainFrame();
            aboutBox = new JavaSnoopAboutBox(mainFrame);
            aboutBox.setLocationRelativeTo(mainFrame);
        }
        JavaSnoop.getApplication().show(aboutBox);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        mainPanel = new javax.swing.JPanel();
        btnAttach = new javax.swing.JButton();
        jLabel5 = new javax.swing.JLabel();
        btnStart = new javax.swing.JButton();
        jLabel2 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel1 = new javax.swing.JLabel();
        javax.swing.JLabel imageLabel = new javax.swing.JLabel();
        progressBar = new javax.swing.JProgressBar();

        mainPanel.setName("mainPanel"); // NOI18N

        javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance(com.aspect.snoop.JavaSnoop.class).getContext().getActionMap(StartupView.class, this);
        btnAttach.setAction(actionMap.get("attachToExisting")); // NOI18N
        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(com.aspect.snoop.JavaSnoop.class).getContext().getResourceMap(StartupView.class);
        btnAttach.setFont(resourceMap.getFont("btnAttach.font")); // NOI18N
        btnAttach.setText(resourceMap.getString("btnAttach.text")); // NOI18N
        btnAttach.setToolTipText(resourceMap.getString("btnAttach.toolTipText")); // NOI18N
        btnAttach.setName("btnAttach"); // NOI18N

        jLabel5.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel5.setText(resourceMap.getString("jLabel5.text")); // NOI18N
        jLabel5.setName("jLabel5"); // NOI18N

        btnStart.setAction(actionMap.get("startNewProcess")); // NOI18N
        btnStart.setFont(resourceMap.getFont("btnStart.font")); // NOI18N
        btnStart.setText(resourceMap.getString("btnStart.text")); // NOI18N
        btnStart.setToolTipText(resourceMap.getString("btnStart.toolTipText")); // NOI18N
        btnStart.setName("btnStart"); // NOI18N

        jLabel2.setFont(resourceMap.getFont("jLabel2.font")); // NOI18N
        jLabel2.setText(resourceMap.getString("jLabel2.text")); // NOI18N
        jLabel2.setName("jLabel2"); // NOI18N

        jLabel4.setText(resourceMap.getString("jLabel4.text")); // NOI18N
        jLabel4.setName("jLabel4"); // NOI18N

        jLabel3.setText(resourceMap.getString("jLabel3.text")); // NOI18N
        jLabel3.setName("jLabel3"); // NOI18N

        jLabel1.setFont(resourceMap.getFont("jLabel1.font")); // NOI18N
        jLabel1.setText(resourceMap.getString("jLabel1.text")); // NOI18N
        jLabel1.setName("jLabel1"); // NOI18N

        imageLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        imageLabel.setIcon(resourceMap.getIcon("imageLabel.icon")); // NOI18N
        imageLabel.setAlignmentX(0.5F);
        imageLabel.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        imageLabel.setName("imageLabel"); // NOI18N

        progressBar.setEnabled(false);
        progressBar.setName("progressBar"); // NOI18N

        javax.swing.GroupLayout mainPanelLayout = new javax.swing.GroupLayout(mainPanel);
        mainPanel.setLayout(mainPanelLayout);
        mainPanelLayout.setHorizontalGroup(
            mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, mainPanelLayout.createSequentialGroup()
                .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(mainPanelLayout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(progressBar, javax.swing.GroupLayout.PREFERRED_SIZE, 284, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(mainPanelLayout.createSequentialGroup()
                            .addContainerGap()
                            .addComponent(btnAttach, javax.swing.GroupLayout.PREFERRED_SIZE, 143, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addComponent(jLabel5, javax.swing.GroupLayout.DEFAULT_SIZE, 86, Short.MAX_VALUE)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addComponent(btnStart, javax.swing.GroupLayout.PREFERRED_SIZE, 143, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGroup(mainPanelLayout.createSequentialGroup()
                            .addComponent(imageLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 138, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, 246, Short.MAX_VALUE)
                                .addComponent(jLabel4, javax.swing.GroupLayout.DEFAULT_SIZE, 246, Short.MAX_VALUE)
                                .addComponent(jLabel3)))
                        .addGroup(mainPanelLayout.createSequentialGroup()
                            .addGap(83, 83, 83)
                            .addComponent(jLabel2))))
                .addContainerGap())
        );
        mainPanelLayout.setVerticalGroup(
            mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(mainPanelLayout.createSequentialGroup()
                .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(imageLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 118, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(mainPanelLayout.createSequentialGroup()
                        .addGap(26, 26, 26)
                        .addComponent(jLabel1)
                        .addGap(27, 27, 27)
                        .addComponent(jLabel3)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(btnAttach, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(btnStart, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jLabel5)))
                .addGap(18, 18, 18)
                .addComponent(progressBar, javax.swing.GroupLayout.DEFAULT_SIZE, 22, Short.MAX_VALUE)
                .addContainerGap())
        );

        setComponent(mainPanel);
    }// </editor-fold>//GEN-END:initComponents

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAttach;
    private javax.swing.JButton btnStart;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JPanel mainPanel;
    private javax.swing.JProgressBar progressBar;
    // End of variables declaration//GEN-END:variables

    private JDialog aboutBox;

    @Action
    public void attachToExisting() {

        ChooseProcessView view = new ChooseProcessView(getFrame(), true);
        view.setVisible(true);

        UIUtil.waitForInput(view);

        final int pid = view.getPid();
        final String mainClass = view.getMainClass();

        if (pid == -1) {// indicates the user cancelled
           return;
        }

        progressBar.setIndeterminate(true);

        progressBar.setString("Building agent...");
        progressBar.setStringPainted(true);

        SwingWorker worker = new SwingWorker() {
            @Override
            protected void done() {
                progressBar.setString("Agent attached! Console should appear momentarily...");
                progressBar.setIndeterminate(false);
            }
            @Override
            protected Object doInBackground() throws Exception {
                try {
                	AgentJar agentJar = AgentJarCreator.createAgentJar(false);
                    String agentJarPath = agentJar.getAgentJarPath();
                    progressBar.setString("Attaching agent...");
                    logger.info("Attaching to process ID " + pid + " with generated agent at " + agentJarPath);
                    AttachUtil.loadAgentInOtherVM(agentJar, Integer.toString(pid), mainClass);
                } catch (AttachNotSupportedException ex) {
                    logger.error(ex);
                    UIUtil.showErrorMessage(getFrame(), "Targeted virtual machine does not support attaching: " + ex.getMessage());
                } catch (IOException ex) {
                    logger.error(ex.getMessage(), ex);
                    UIUtil.showErrorMessage(getFrame(), "Could not attach to new virtual machine due to I/O error: " + ex.getMessage());
                } catch (AgentLoadException ex) {
                    logger.error(ex);
                    UIUtil.showErrorMessage(getFrame(), "Could not load agent: " + ex.getMessage());
                } catch (AgentInitializationException ex) {
                    logger.error(ex.getMessage(), ex);
                    UIUtil.showErrorMessage(getFrame(), "Could not initialize agent: " + ex.getMessage());
                } catch (AgentCommunicationException ex) {
                    logger.error(ex);
                    UIUtil.showErrorMessage(getFrame(), "Could not communicate with agent. It's possible that this process has already been attached to once.");
                }

                return null;
            }
        };

        worker.execute();
    }

    @Action
    public void startNewProcess() {
        NewProcessInfoView view = new NewProcessInfoView(getFrame(),true);
        view.setVisible(true);

        UIUtil.waitForInput(view);

        final SnoopSession session = view.getSnoopSession();

        if (session == null) // indicates the user cancelled
           return;

        progressBar.setIndeterminate(true);

        progressBar.setString("Building agent...");
        progressBar.setStringPainted(true);

        SwingWorker worker = new SwingWorker() {
            @Override
            protected void done() {
                progressBar.setString("Process started! Console should appear momentarily...");
                progressBar.setValue(0);
                progressBar.setIndeterminate(false);
            }
            @Override
            protected Object doInBackground() throws Exception {
                try {
                	AgentJar agentJar = AgentJarCreator.createAgentJar(false);
                    String agentJarPath = agentJar.getAgentJarPath();
                    progressBar.setString("Starting process with agent...");
                    logger.info("Starting new process with generated agent at " + agentJarPath);
                    AttachUtil.launchInNewVM(agentJar, session);
                } catch (AttachNotSupportedException ex) {
                    logger.error(ex);
                    UIUtil.showErrorMessage(getFrame(), "Targeted virtual machine does not support attaching: " + ex.getMessage());
                } catch (IOException ex) {
                    logger.error(ex);
                    UIUtil.showErrorMessage(getFrame(), "Could not attach to new virtual machine due to I/O error: " + ex.getMessage());
                } catch (AgentCommunicationException ex) {
                    logger.error(ex);
                    UIUtil.showErrorMessage(getFrame(), "Could not communicate with agent. It's possible that this process has already been attached to once.");
                }

                return null;
            }
        };

        worker.execute();
    }

}